import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django.settings")
import django
django.setup()
from django.shortcuts import render, redirect,HttpResponse, render_to_response
from salesRecord.models import *

# Create your views here.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 所有门店销售记录
def index(request):
    if request.method == 'POST':
        # 获取流水号
        id = request.POST.get('id')
        # 获取商品编号
        commodity_id = request.POST.get('commodity_id')
        # 获取销售日期
        date = request.POST.get('date')
        # 获取会员编号
        customer_id = request.POST.get('customer_id')
        # 获取门店编号
        supermarket_id = request.POST.get('supermarket_id')

        # 定一个字典用于保存前端发送过来的查询条件
        search_dict = dict()
        # 如果有这个值 就写入到字典中去
        if id:
            search_dict['id'] = id
        if commodity_id:
            search_dict['commodity_id'] = commodity_id
        if date:
            search_dict['date__icontains'] = date
        if customer_id:
            search_dict['customer_id'] = customer_id
        if supermarket_id and supermarket_id != "0000":
            search_dict['supermarket_id'] = supermarket_id

        # 多条件查询 关键点在这个位置传如的字典前面一定要加上两个星号.
        record_list = Salesrecord.objects.filter(**search_dict)

        return render(request, 'sale.html', {'record_list': record_list, 'market_id': "index"})

    else:
        record_list = Salesrecord.objects.all()     # 依据门店id查询对应的销售记录
        return render(request, 'sale.html', {'record_list': record_list, 'market_id': "index"})


def record_list(request, market_id):
    if request.method == 'POST':
        # 获取流水号
        id = request.POST.get('id')
        # 获取商品编号
        commodity_id = request.POST.get('commodity_id')
        # 获取销售日期
        date = request.POST.get('date')
        # 获取会员编号
        customer_id = request.POST.get('customer_id')

        # 定一个字典用于保存前端发送过来的查询条件
        search_dict = dict()
        # 如果有这个值 就写入到字典中去
        if id:
            search_dict['id'] = id
        if commodity_id:
            search_dict['commodity_id'] = commodity_id
        if date:
            search_dict['date__icontains'] = date
        if customer_id:
            search_dict['customer_id'] = customer_id

        # 指定对应的门店id
        search_dict['supermarket_id'] = market_id

        # 多条件查询 关键点在这个位置传如的字典前面一定要加上两个星号.
        record_list = Salesrecord.objects.filter(**search_dict)
        return render(request, 'sale.html', {'record_list': record_list, 'market_id': market_id})

    else:
        record_list = Salesrecord.objects.filter(supermarket_id = market_id)    # 依据门店id查询对应的销售记录
        return render(request, 'sale.html', {'record_list': record_list, 'market_id': market_id})

# 总店销售记录
def sm1_list(request):
    return record_list(request, "0001")

# 门店1销售记录
def sm2_list(request):
    return record_list(request, "0002")

# 门店2销售记录
def sm3_list(request):
    return record_list(request, "0003")